using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MVCDemo.Db;
using MVCDemo.Models;

namespace MVCDemo.Repository
{
    public class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly SoftDb db;
        private readonly DbSet<T> tab;
        public EfRepository()
        {
            db=new SoftDb();
            tab=db.Set<T>();
        }
        public IQueryable<T> Table
        {
            get{
                return tab as IQueryable<T>;
            }
        }
        public void Insert(T entity)
        {
            entity.IsDeleted=false;
            entity.IsActived=true;
            entity.UpdateTime=DateTime.Now;
            entity.DisplayOrder=0;
            entity.Creator=0;
            tab.Add(entity);
            db.SaveChanges();
        }
        public void Update(T entity)
        {
            if (entity==null){
                throw new System.Exception();
            }if (entity.Id==0){
                throw new System.Exception();
            }
            entity.UpdateTime=DateTime.Now;
            tab.Update(entity);
            db.SaveChanges();
        }
        public void Delete(int id)
        {
            var entity=tab.Where(x=>x.Id==id).FirstOrDefault();
            if (entity!=null){
                entity.UpdateTime=DateTime.Now;
                entity.IsDeleted=true;
            }
            tab.Update(entity);
            db.SaveChanges();
        }
        public T GetById(int id)
        {
            var entity = tab.Where(x=>x.Id==id && x.IsDeleted==false).FirstOrDefault();
            return entity;
        }
    }
}